#!/bin/bash
#获取当前的目录
CUR_PATH=$(readlink -f $(dirname $0))
#判断config.ini是否存在
if [ ! -e $CUR_PATH/config.ini ]; then
    echo "Config File config.ini is not exists..please check..."
    exit 1
fi

#判断日志文件是否存在。如果存在则删除掉
if [ -e $CUR_PATH/disk_format.log ]; then
    rm -f $CUR_PATH/disk_format.log
fi

# 根据上条指令执行结果正确与否输出对应信息
function result_echo() {
    if [ $? -eq 0 ]; then
        echo "$1" | tee -a >>$CUR_PATH/disk_format.log
    else
        echo "$2" | tee -a >>$CUR_PATH/disk_format.log
        exit 1
    fi
}

cat $CUR_PATH/config.ini | sed -n '/\[Disk_Format\]/,/\[.*\]/p' | grep -v '\[.*\]' | grep -v \^\# | grep -v \^[[:space:]]\*\$ >/tmp/Format_Info
cat $CUR_PATH/config.ini | sed -n '/\[Disk_Format\]/,/\[.*\]/p' | grep -v '\[.*\]' | grep -v \^\# | grep -v \^[[:space:]]\*\$ | awk '{print $1}' >/tmp/Format_Hosts

for host in $(cat /tmp/Format_Hosts); do
    ansible -i /tmp/Format_Hosts $host -m ping
    result_echo "OK...Connect To Host $host Success" "Sorry,Connect To Host $host Failed...Please Check..."
    Mount_path=$(cat /tmp/Format_Info | awk -v h=$host '$1==h{print $2}')
    echo $Mount_path | grep "^/.*" &>/dev/null
    if [ $? -ne 0 ]; then
        echo "Sorry,Disk Mount Path $Mount_path Does Not Begin With '/'"
        exit 1
    fi
    ansible -i /tmp/Format_Hosts $host -m shell -a 'rm -f /tmp/formatting.sh'
    ansible -i /tmp/Format_Hosts $host -m copy -a "src=formatting.sh dest=/tmp"
    ansible -i /tmp/Format_Hosts $host -m shell -a "bash /tmp/formatting.sh $Mount_path"
    result_echo "OK...The Disk is formatted and successfully mounted to $Mount_path" "Sorry,Disk Formatted and Mounted Failed...Please Check..."
done
